package tr.edu.ege.kipler.satisfiability.blocking;

import java.util.Iterator;

import tr.edu.ege.kipler.satisfiability.container.ABox;
import tr.edu.ege.kipler.satisfiability.container.Individual;
import tr.edu.ege.kipler.satisfiability.container.SHIQABox;
import tr.edu.ege.kipler.satisfiability.container.operational.SHIQAncestorCollector;

/**
 * 
 * @author İnanç Seylan
 *
 */
public abstract class SHIQABoxBlocking implements BlockingStrategy {
	private SHIQABox aBox;

	protected void setABox(ABox abox) {
		this.aBox = (SHIQABox) abox;
	}

	protected SHIQABox getABox() {
		return aBox;
	}

	abstract protected boolean isBlockingConditionSatisfied(String individual);

	public boolean isBlocked(ABox abox, String individual) {
		setABox(abox);
		return isBlockingConditionSatisfied(individual)
				|| isIndirectlyBlocked(abox, individual);
	}

	public boolean isDirectlyBlocked(ABox abox, String individual) {
		setABox(abox);
		boolean result = isBlockingConditionSatisfied(individual);
		if (result) {
			Individual x = abox.getIndividual(individual.toString());
			for (Individual ancestor : new SHIQAncestorCollector(getABox(), x)
					.collect()) {
				if (isBlockingConditionSatisfied(ancestor.getName())) {
					result = false;
					break;
				}
			}
		}
		return result;
	}

	public boolean isIndirectlyBlocked(ABox abox, String indvName) {
		setABox(abox);
		boolean result = false;
		Individual x = abox.getIndividual(indvName.toString());
		for (Individual ancestor : new SHIQAncestorCollector(getABox(), x)
				.collect()) {
			if (isBlockingConditionSatisfied(ancestor.getName())) {
				result = true;
				break;
			}
		}
		return result;
	}

	protected Individual getPredecessor(Individual individual) {
		Iterator<Individual> i = aBox.predecessorIterator(individual);
		Individual result = i.hasNext() ? i.next() : null;
		return result;
	}

}
